package com.houfukude.Utils;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;

import Utils.V;

/**
 * FTP_Server封装管理类
 * 
 * @author houfukude
 * 
 */
public class FTP_Server {
	// private String DEBUG_TAG = "FTP_Utils";

	private FtpServer ftpServer;

	private int port = 2221;
	private String path = V.DIR + "/";
	private String usr = "anonymous";
	private String pwd = null;
	/**
	 * IPv6 关闭
	 */
	static {
		System.setProperty("java.net.preferIPv6Addresses", "false");
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void setUsr(String usr) {
		this.usr = usr;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	/**
	 * 启动服务
	 * 
	 * @return
	 */
	public Boolean start() {
		if (ftpServer == null) {
			FtpServerFactory serverFactory = new FtpServerFactory();
			ListenerFactory factory = new ListenerFactory();
			// set the port of the listener
			factory.setPort(port);
			// replace the default listener
			serverFactory.addListener("default", factory.createListener());
			BaseUser user = new BaseUser();
			user.setName(usr);
			user.setPassword(pwd);
			user.setHomeDirectory(path);
			try {
				serverFactory.getUserManager().save(user);
				ftpServer = serverFactory.createServer();
				// start the server
				ftpServer.start();
				return true;
			} catch (FtpException e) {	
				ftpServer =null;
				e.printStackTrace();
			}
		}
	
		return false;

	}

	/**
	 * 停止服务
	 * 
	 * @return
	 */
	public Boolean stop() {
		if (null != ftpServer) {
			ftpServer.stop();
			ftpServer = null;
			return true;
		}
		return false;

	}

}
